package com.csmk.springboot_simple.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import com.csmk.springboot_simple.common.PageRes;
import com.csmk.springboot_simple.common.R;
import com.github.pagehelper.Page;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 91cxk
 * 统一返回处理
 */
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 如果不需要进行封装的，可以添加一些校验手段，比如添加标记排除的注解
        return true;
    }

    /**
     * controller中的方法都会从这经过
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, org.springframework.http.server.ServerHttpRequest serverHttpRequest, org.springframework.http.server.ServerHttpResponse serverHttpResponse) {
        // 由spring抛出的异常状态码非200的不处理
        if (serverHttpResponse instanceof org.springframework.http.server.ServletServerHttpResponse) {
            int status = ((org.springframework.http.server.ServletServerHttpResponse) serverHttpResponse).getServletResponse().getStatus();

            // 如果是错误状态码，直接返回原始对象
            if (status != 200) {
                return o;
            }
        }
        if(o==null){
            // controller方法返回值为void 统一响应一个成功
            return R.success();
        }
        if (o instanceof R || o instanceof JSONObject) {
            return o;
        }
        if (o instanceof String){
            // 字符串需另外处理
            return JSON.toJSONString(R.success(o));
        }
        if(o instanceof Page){
            // 传来的是Page类则需要分页处理
            return R.success(PageRes.of((Page<?>)o));
        }
        return R.success(o);
    }

}
